﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Common.Model;
using Yipusoft.Common.BLL;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.SoldierArchives.BLL;
using System.Drawing;
using Yipusoft.SoldierArchives.Model;

public partial class BasicBase_SoldierArchive_SoldierSelect : System.Web.UI.Page
{
    //private string strName.Value;
    protected void Page_Load(object sender, EventArgs e)
    {
        //BindNation();
        if (!Page.IsPostBack)
        {
            BindProvince();
            //BindBackground();
            BindCulture();
            //BindReligion();
            BindCities(ddlProvinces.SelectedValue);

            BindDepartment();

            if (Request["Uid"] != null)
            {
                BindSoldiers(Request["Uid"], 20, 0);
            }
            BindPolitical();
            BindHobby();
            //BindCustom();

            // TabContainer1.ActiveTabIndex = 0;

        }

    }
    private void BindPolitical()
    {
        ListItem blankLI = new ListItem("", "");
        ddlPolitical.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='ZZMM00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlPolitical.Items.Add(li);
        }
    }

    private void BindHobby()
    {
        ListItem blankLI = new ListItem("", "");
        ddlHobby.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='XQAH00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlHobby.Items.Add(li);
        }
    }

    private void BindCustom(string strsql)
    {
        NewSoldier soldier = new NewSoldier();
        int totalCount = soldier.GetSoldiersCountByWhere(strsql);

    }


    private void BindProvince()
    {
        //ddlProvinces.DataSource = CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID");
        //ddlProvinces.DataTextField = "ItemName";
        //ddlProvinces.DataValueField = "ItemID";
        //ddlProvinces.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlProvinces.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='SS000000' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlProvinces.Items.Add(li);
        }
    }

    private void BindCulture()
    {
        //ddlCulture.DataSource = CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID");
        //ddlCulture.DataTextField = "ItemName";
        //ddlCulture.DataValueField = "ItemID";
        //ddlCulture.DataBind();
        ListItem blankLI = new ListItem("", "");
        ddlCulture.Items.Add(blankLI);
        foreach (CodeItemInfo item in CodeItem.GetList("ParentID='WHCD00' ORDER BY SeqID"))
        {
            ListItem li = new ListItem(item.ItemName, item.ItemID);
            ddlCulture.Items.Add(li);
        }
    }


    protected void ddlProvinces_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCities(ddlProvinces.SelectedValue);
    }

    private void BindCities(string province)
    {
        //ddlCities.DataSource = CodeItem.GetList("ParentID='"+province+"' Order by SeqID");
        //ddlCities.DataTextField = "ItemName";
        //ddlCities.DataValueField = "ItemID";
        //ddlCities.DataBind();
        ddlCities.Items.Clear();
        if (province.Trim() == "")
        {
            ListItem blankLI = new ListItem("", "");
            ddlCities.Items.Add(blankLI);
        }
        else
        {
            foreach (CodeItemInfo item in CodeItem.GetList("ParentID='" + province + "' Order by SeqID"))
            {
                ListItem li = new ListItem(item.ItemName, item.ItemID);
                ddlCities.Items.Add(li);
                foreach (CodeItemInfo subItem in CodeItem.GetList("ParentID='" + item.ItemID + "' Order by SeqID"))
                    ddlCities.Items.Add(new ListItem("\u3000" + subItem.ItemName, subItem.ItemID));
            }
        }
    }


    private void BindDepartment()
    {
        string DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        ddlSection.Items.Clear();

        List<DepartmentInfo> list = new List<DepartmentInfo>();
        if (DepartmentId.Substring(0, 4) == "1300")
        {
            ddlSection.Items.Add(new ListItem("", ""));
            list = Department.GetList("departmentId like '%000'");
            foreach (DepartmentInfo info in list)
            {
                ddlSection.Items.Add(new ListItem(info.FullName, info.DepartmentID));
            }
        }
        else
        {
            list = Department.GetList("departmentId = '" + DepartmentId.Substring(0, 4) + "000'");
            foreach (DepartmentInfo info in list)
            {
                ddlSection.Items.Add(new ListItem(info.FullName, info.DepartmentID));
            }
        }

    }

    private List<DepartmentInfo> GetDepartmentList(string departmentID, string permissionLevel, string permissionUnit)
    {
        List<DepartmentInfo> departmentList = new List<DepartmentInfo>();
        if (Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionLevel) || Yipusoft.Account.BLL.User.HasPermission(Context.User.Identity.Name, permissionUnit))
            departmentList = Department.GetList("DepartmentID='" + departmentID.Substring(0, 4) + "000'");
        return departmentList;
    }



    private void InsertContainValue(string contains, string containsName)
    {
        if (strSql.Value != "")
        {
            if (!strSql.Value.Contains(contains))
            {
                strSql.Value += " and " + contains;
                strName.Value += containsName;
            }
        }
        else
        {
            strSql.Value = contains;
            strName.Value = containsName;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        strSql.Value = "";
        if (SoldierName.Text.Trim() != "")
        {
            string Name1 = SoldierName.Text;
            Name1 = Name1.Replace(" ", "");
            string Name = "";
            foreach (char c in Name1)
            {
                Name += "%" + c;
            }
            Name += "%";

            InsertContainValue("SoldierName like '" + Name + "' ", " 姓名中包含'" + SoldierName.Text + "' ");

        }


        if (ddlSex.SelectedValue != "")
        {

            InsertContainValue("Sex='" + ddlSex.SelectedValue + "'", " 性别为" + ddlSex.SelectedValue);

        }

        if (ddlCities.SelectedValue != "")
        {
            InsertContainValue("Native='" + ddlCities.SelectedValue + "'", " 籍贯为" + ddlProvinces.SelectedItem.Text + ddlCities.SelectedItem.Text);
        }



        if (Birthday.Text != "")
        {
            InsertContainValue("Birth" + ddlBirthOperater.SelectedValue + "'" + Birthday.Text + "'", " 出生日期" + ddlBirthOperater.SelectedItem.Text + Birthday.Text);
        }


        if (ddlCulture.SelectedValue != "")
        {
            InsertContainValue("Culture='" + ddlCulture.SelectedValue + "'", " 文化程度为" + ddlCulture.SelectedItem.Text);
        }

        if (ddlPolitical.SelectedValue != "")
        {
            InsertContainValue("Political='" + ddlPolitical.SelectedValue + "'", "政治面貌为" + ddlPolitical.SelectedItem.Text);

        }

        if (ddlHobby.SelectedValue != "")
        {
            InsertContainValue("Hobby='" + ddlHobby.SelectedValue + "'", " 特长为" + ddlHobby.SelectedItem.Text);

        }
        if (ddlSection.SelectedValue != "")
        {
            InsertContainValue("departmentid='" + ddlSection.SelectedValue + "'", " 单位为" + ddlSection.SelectedItem.Text);
        }

        BindSoldiers(strSql.Value, 20, 0);


    }

    private void BindSoldiers(string sql, int pageSize, int pageIndex)
    {
        lblWhere.Text = sql;
        if (!panPage.Visible)
            panPage.Visible = true;
        NewSoldier soldier = new NewSoldier();
        int totalCount = soldier.GetSoldiersCountByWhere(sql);
        ViewState["PageCount"] = Convert.ToInt32(Math.Ceiling((double)totalCount / pageSize));
        if ((int)ViewState["PageCount"] < pageIndex)
            pageIndex = pageIndex - 1;
        ViewState["PageIndex"] = pageIndex;
        gvSoldiers.DataSource = soldier.GetSoldiersByWhere(sql, "DepartmentID,setTime", "Asc", pageSize, pageIndex);
        gvSoldiers.DataBind();
        lbGridInfo.Text = "共有<b>" + totalCount.ToString() + "</b>条记录 第<b>" + ((int)ViewState["PageIndex"] + 1).ToString() + "</b>页 共<b>" + ViewState["PageCount"].ToString() + "</b>页 每页<b>" + pageSize.ToString() + "</b>条";
        this.btnFirst.Enabled = (int)ViewState["PageIndex"] > 0;
        this.btnPrev.Enabled = (int)ViewState["PageIndex"] > 0;
        this.btnNext.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
        this.btnLast.Enabled = (int)ViewState["PageIndex"] < (int)ViewState["PageCount"] - 1;
        BindJumpList();
    }

    protected void JumpList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSoldiers(strSql.Value, 20, int.Parse(JumpList.SelectedValue));
    }
    protected void btnFirst_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = 0;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnPrev_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] - 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageIndex"] + 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    protected void btnLast_Click(object sender, EventArgs e)
    {
        ViewState["PageIndex"] = (int)ViewState["PageCount"] - 1;
        BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
    }
    private void BindJumpList()
    {
        JumpList.Items.Clear();
        ListItem li;
        for (int i = 0; i < (int)ViewState["PageCount"]; i++)
        {
            li = new ListItem();
            li.Text = (i + 1).ToString();
            li.Value = i.ToString();
            JumpList.Items.Add(li);
        }
        JumpList.SelectedIndex = JumpList.Items.IndexOf(JumpList.Items.FindByValue(ViewState["PageIndex"].ToString()));
    }
    protected void gvSoldiers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string accountDepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;

        bool endableDelete = false;
        if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203001"))
            endableDelete = true;
        else
            if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203008") && accountDepartmentID.Substring(0, 4) == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString().Substring(0, 4))
                endableDelete = true;
            else
                if (Yipusoft.Account.BLL.User.HasPermission(User.Identity.Name, "203009") && accountDepartmentID == gvSoldiers.DataKeys[e.RowIndex].Values["DepartmentID"].ToString())
                    endableDelete = true;
        if (endableDelete)
        {
            NewSoldier soldier = new NewSoldier();
            SoldierArchiveInfo info = soldier.GetSoldierInfoByID(gvSoldiers.DataKeys[e.RowIndex].Values["SoldierID"].ToString());
            string name = info.SoldierName;
            if (soldier.Delete(gvSoldiers.DataKeys[e.RowIndex].Values["SoldierID"].ToString(), "人工删除", DateTime.Now, User.Identity.Name, Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName))
            {
                EventLogInfo log = new EventLogInfo();
                log.EventTime = DateTime.Now;
                log.EventType = 1;


                log.EventData = "删除士兵";

                log.ItemID = name;
                log.ItemName = "BasicBase";
                log.ItemFullUrl = "SoldierArchive/NewEmployee.aspx";
                log.CreatedBy = Context.User.Identity.Name;
                log.CreatedTime = DateTime.Now;
                log.UserIP = Request.UserHostAddress;
                EventLog.Insert(log);
                BindSoldiers(strSql.Value, 20, (int)ViewState["PageIndex"]);
                lblUpdataResult.Text = "删除成功！";
            }


        }

    }

    protected void gvSoldiers_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label ID = (Label)e.Row.FindControl("ID");
            ID.Text = (int.Parse(ViewState["PageIndex"].ToString()) * 20 + e.Row.RowIndex + 1).ToString();
            //当鼠标放上去的时候 先保存当前行的背景颜色 并给附一颜色 
            e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor='#F5F5F5',this.style.fontWeight='';");
            //当鼠标离开的时候 将背景颜色还原的以前的颜色 
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor,this.style.fontWeight='';");
            SoldierArchiveInfo soldier = e.Row.DataItem as SoldierArchiveInfo;
            System.Web.UI.HtmlControls.HtmlAnchor AName = e.Row.FindControl("AName") as System.Web.UI.HtmlControls.HtmlAnchor;

            AName.InnerText = soldier.SoldierName;
            ImageButton btnEdit = e.Row.FindControl("btnEdit") as ImageButton;
            if (soldier.IsContract)
            {
                //AName.HRef = "javascript:OpenWin('EmployeeView.aspx?ID=" + soldier.SoldierID + "')";

                AName.HRef = "EmployeeView.aspx?ID=" + soldier.SoldierID;
                btnEdit.PostBackUrl = "NewEmployee.aspx?ID=" + soldier.SoldierID;
            }
            else
            {
                //AName.HRef = "javascript:OpenWin('SoldierView1.aspx?ID=" + soldier.SoldierID + "')";
                AName.HRef = "SoldierView1.aspx?ID=" + soldier.SoldierID;
                btnEdit.PostBackUrl = "NewSoldier.aspx?ID=" + soldier.SoldierID;
            }


        }

    }


    protected void export_Click(object sender, EventArgs e)
    {
        if (gvSoldiers.Rows.Count != 0)
        {
            Session["Where"] = lblWhere.Text;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PrintDutyScript()", "<script type='text/javascript'> print();</script>");
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "PrintDutyScript()", "<script type='text/javascript'>alert('没有输出内容,请重新查询');</script>");
        }
    }

    public List<DepartmentInfo> getHaveSoldierDepartmentList(string where, string isContract)
    {
        NewSoldier soldier = new NewSoldier();
        List<string> soldierDepartment = new List<string>();
        if (isContract == "")
        {
            soldierDepartment = soldier.GetHaveSoldierDepartmentIDs(where + " and IsDelete=0 ");
        }
        else
        {
            soldierDepartment = soldier.GetHaveSoldierDepartmentIDs(where + " and IsDelete=0 and IsContract=" + Convert.ToInt32(isContract));
        }

        List<DepartmentInfo> departmentList = Department.GetList(where);
        departmentList = (from p in departmentList where soldierDepartment.Contains(p.DepartmentID) select p).ToList();
        return departmentList;
    }

    protected void lkbUpdata_Click(object sender, EventArgs e)
    {
        string departmentid = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        NewSoldier sodier = new NewSoldier();
        string sodierWhere = " IsDelete=0 and IsContract=0 and Departmentid like '" + departmentid.Substring(0, 4) + "%'";
        string ContractWhere = " IsDelete=0 and IsContract=1 and Departmentid like '" + departmentid.Substring(0, 4) + "%'";
        int sodierCount = sodier.GetSoldiersCountByWhere(sodierWhere);
        int ContractCount = sodier.GetSoldiersCountByWhere(ContractWhere);
        if (SoldierUpdate.UpdataInfo(departmentid.Substring(0, 4) + "000", sodierCount, ContractCount, User.Identity.Name) != Guid.Empty)
        {
            lblUpdataResult.Text = "" + Department.GetDepartment(departmentid.Substring(0, 4) + "000").AliasName + "士兵数更新完成：当前现役士兵数为：" + sodierCount + ",当前合同制队员为：" + ContractCount;
        }
        else
        {
            lblUpdataResult.Text = "更新失败";
        }
    }

}
